﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SharpShare.Storage.Filter {
    internal sealed class FilteredStorageLookup : IStorageLookup {
        private IStorageLookup _baseLookup;
        private IStorageLookup _modifiedLookup;

        public FilteredStorageLookup(FilteredStorageContainer container) {
            this.Container = container;
            _baseLookup = container.BaseItem.Contents;
            _modifiedLookup = container.Filter.ModifyContents(new FilterScope<IStorageContainer>(container.BaseItem, container), _baseLookup);
        }

        public FilteredStorageContainer Container { get; private set; }

        #region IStorageLookup Members

        public int Count {
            get { return _modifiedLookup.Count; }
        }

        public IStorageItem this[string name] {
            get {
                IStorageItem item = _modifiedLookup[name];

                return WrapChild(item);
            }
        }

        #endregion

        private IEnumerable<FilteredStorageItem> ListWrappedContents() {
            foreach (IStorageItem item in _modifiedLookup) {
                FilteredStorageItem wrapped = WrapChild(item);
                if (wrapped != null) {
                    yield return wrapped;
                }
            }
        }

        #region IEnumerable<IStorageItem> Members

        public IEnumerator<IStorageItem> GetEnumerator() {
            return this.ListWrappedContents().GetEnumerator();
        }

        #endregion

        #region IEnumerable Members

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
            return this.GetEnumerator();
        }

        #endregion

        private FilteredStorageItem WrapChild(IStorageItem item) {
            if (item == null) {
                return null;
            }

            IStorageContainer containerChild = item.AsContainer();

            if (containerChild != null) {
                return FilteredStorageContainer.Create(containerChild, this.Container.Filter, this.Container);
            }

            IStorageFile fileChild = item.AsFile();

            if (fileChild != null) {
                return FilteredStorageFile.Create(fileChild, this.Container.Filter, this.Container);
            }

            return null;
        }
    }
}
